<template>
  <view>
    <view class="search-box">
      <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    </view>


    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length!==0">
      <view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDateil(item)">
        <view class="sugg-name">
          {{item.goods_name}}
        </view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索建议列表结束 -->


    <!-- 历史记录列表 -->
    <view class="history-box" v-else>
      <!-- 标题 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="18" @click="cleanHistory"></uni-icons>
      </view>
      <!-- 列表 -->
      <view class="history-list">
        <uni-tag @click="gotoGoodsList(item)" :text="item" v-for="item,i in historys" :key="i"></uni-tag>
      </view>
    </view>
    <!-- 历史记录结束 -->
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null, //做防抖处理
        keyword: '', //搜素的关键词
        searchResults: [], //搜素结果列表
        historyList: ['a', 'va', 'saf'], //历史记录
      };
    },
    onLoad(){
     this.historyList= JSON.parse(uni.getStorageSync('kw')||[])
    
    },
    computed: {
      historys() {
        // 注意：由于数组是引用类型，所以不要直接基于原数组调用 reverse 方法，以免修改原数组中元素的顺序
        // 而是应该新建一个内存无关的数组，再进行 reverse 反转
        return [...this.historyList].reverse()
      }
    },
    methods: {
      // ipt输入事件的处理函数
      input(e) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.keyword = e
          console.log(e)
          this.getSearchResults()
        }, 500)
      },

      async getSearchResults() {
        // 首先要判断关键词是否为空
        if (this.keyword.length === 0) {
          this.searchResults = []
          return
        } else {
          const {
            data: res
          } = await uni.$http.get('/api/public/v1/goods/qsearch', {
            query: this.keyword
          })
          console.log(res)
          if (res.meta.status !== 200) return uni.$showMsg()
          this.searchResults = res.message
          this.savaSearchHistory()
        }
      },
      // 跳转到详情页
      gotoDateil(item) {
        console.log(item.goods_id)
        this.keyword=''
        uni.navigateTo({
          url: '../goods_dateil/goods_dateil?goods_id=' + item.goods_id
        })
      },
      // 保存历史记录
      savaSearchHistory() {
        // this.historyList.unshift(this.keyword)
        const set = new Set(this.historyList)
        set.delete(this.keyword)
        set.add(this.keyword)
        console.log(set)
        this.historyList = Array.from(set)
        // 将历史记录本地保存起来
        uni.setStorageSync('kw',JSON.stringify(this.historyList))
      },
      //清空历史记录
      cleanHistory(){
        this.historyList=[]
        uni.setStorageSync('kw','[]')
      },
     //点击历史记录跳转到商品详情
      gotoGoodsList(item){
         uni.navigateTo({
            url: '/subpkg/goods_list/goods_list?query=' + item
          })
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    .sugg-item {
      height: 80rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20rpx;
      border-bottom: 2px solid #efefef;

      .sugg-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 24rpx;
      }
    }
  }

  .history-box {
    display: flex;
    flex-direction: column;

    .history-title {

      display: flex;
      justify-content: space-between;
      padding: 20rpx 10rpx;
      border-bottom: 4rpx solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .uni-tag {
        background: #efefef;
        border: none;
        color: #000;
        margin-left: 20rpx;
        line-height: 100rpx;
        padding: 20rpx;
      }
    }
  }
</style>
